package com.zk.qqrobot.service;

import com.zk.qqrobot.config.Constant;
import com.zk.qqrobot.model.Reward;
import com.zk.qqrobot.util.ComputeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import static java.util.Comparator.comparing;

@Slf4j
@Service
public class RewardService {

    @Autowired
    private RedisService<String, Reward> redisService;

    public String save(Reward reward,String group){
        Reward catshR = redisService.hashGet(Constant.REWARD_KEY.concat(group), reward.getNick());
        if (Objects.isNull(catshR)){
            redisService.hashPut(Constant.REWARD_KEY.concat(group),reward.getNick(),reward);
        }else{
            catshR.setRewardTotal(ComputeUtil.compute(catshR.getRewardTotal(),reward.getRewardTotal(),ComputeUtil.ADD));
            redisService.hashPut(Constant.REWARD_KEY.concat(group),catshR.getNick(),catshR);
        }
        return Constant.SUCCESS;
    }

    public String getTop5(String group){
        StringBuffer b = new StringBuffer();
        Double sum = 0.00;
        Double comput = 0.00;
        Integer size = 0;
        Map<String, Reward> rewardMap = redisService.hashEntries(Constant.REWARD_KEY.concat(group));
        if(!Objects.isNull(rewardMap)){
            List<Reward> rewards = new ArrayList<>(rewardMap.values());
            rewards.sort(comparing(Reward::getRewardTotal).reversed());
            for(Reward x:rewards){
                b.append(x.getNick()).append("==").append(x.getRewardTotal()).append("￥").append("\n");
                sum = ComputeUtil.compute(sum,x.getRewardTotal(),ComputeUtil.ADD);
            }
            comput =  ComputeUtil.compute(Constant.BIG_VIP,sum,ComputeUtil.REDUCE);
            size = rewards.size();
        }

        return StringUtils.isEmpty(b.toString()) ? "╮(╯▽╰)╭还没有人打赏" : b.toString() +
                "---------\n总打赏：" + sum + "￥\n距离穷群主的大会员还差：" + comput + "￥" +
                "\n总打赏人数：" + size + "人" + "\n※※※※※※※※※\n感谢榜上老铁支持\n共创良好白嫖环境！！";
    }

}
